package com.alex.core.ip;


import org.apache.http.util.TextUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author: Administrator
 * @ClassName: IPUtils
 * @Date: 2019/10/25 13:42
 * @Description:
 */
public class IPUtils {
    private static final String UNKNOWN = "unknown";

    /**
     * 获取真实的客户端IP地址
     * @param request
     * @return
     */
    public static String getClientRealIp(HttpServletRequest request){
        String remoteip = request.getHeader("remoteip");  //经过阿里负载均衡
        if(!TextUtils.isBlank(remoteip)){
            return remoteip;
        }
        String x_real_ip = request.getHeader("x-real-ip");  //经过NGINX
        if(!TextUtils.isBlank(x_real_ip)){
            return x_real_ip;
        }
        String x_forwarded_for = request.getHeader("x-forwarded-for");   //经过多层网关
        if(!TextUtils.isBlank(x_forwarded_for)){
            return x_forwarded_for.split(",")[0];
        }
        return request.getRemoteAddr();
    }
    /**
     * 判断操作系统
     *
     * @return String
     */
    public static boolean isWindowsOS(){
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if(osName.toLowerCase().contains("windows")){
            isWindowsOS = true;
        }
        return isWindowsOS;
    }


    /**
     * 获取本机ip地址，并自动区分Windows还是linux操作系统
     * @return String
     */
    public static String getLocalIP(){
        String sIP = "";
        InetAddress inetAddress = null;
        try {
            //如果是Windows操作系统
            if(isWindowsOS()){
                inetAddress = InetAddress.getLocalHost();
            }
            //如果是Linux操作系统
            else{
                boolean bFindIP = false;
                Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
                while (netInterfaces.hasMoreElements()) {
                    NetworkInterface ni = netInterfaces.nextElement();
                    //----------特定情况，可以考虑用ni.getName判断
                    //遍历所有ip
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        inetAddress = ips.nextElement();
                        if( inetAddress.isSiteLocalAddress() && !inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().contains(":")){  //127.开头的都是lookback地址
                            bFindIP = true;
                            break;
                        }
                    }
                    if(bFindIP){
                        break;
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        if(null != inetAddress){
            sIP = inetAddress.getHostAddress();
        }
        return sIP;
    }


}
